package org.springblogs.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class HttpUtils {
	
	public static String get(String url, String encoding) {
		return get(url, encoding, false);
	}
	public static String get(String url, String encoding, boolean keepLF) {

		BufferedReader br = null;
		CloseableHttpResponse response = null;
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet(url);
		StringBuffer sb = new StringBuffer();
		try {
			response = httpclient.execute(httpGet);
			if (response.getStatusLine().getStatusCode() != 200) {
				throw new Exception("request failed : " + response.getStatusLine().getStatusCode());
			}
			HttpEntity entity = response.getEntity();

			InputStream is = entity.getContent();
			InputStreamReader isr = new InputStreamReader(is, encoding);
			br = new BufferedReader(isr);

			String line;
			while ((line = br.readLine()) != null) {
				sb.append(line);
				if(keepLF){
					sb.append(StringUtils.LF);
				}
			}

		} catch (Exception e) {
			System.out.println(e.getMessage());
		} finally {
			IOUtils.close(br);
			IOUtils.close(response);
			IOUtils.close(httpclient);
		}
		return sb.toString();
	}
}
